package com.alan.base.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.alan.base.App;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Utils {

    @SuppressLint("SimpleDateFormat")
    public static String getNow() {
        long millis = System.currentTimeMillis();
        Date date = new Date();
        date.setTime(millis);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
        return simpleDateFormat.format(date);
    }

    public static int getAttrInteger(@NonNull Context context, int attrRes) {
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(attrRes, typedValue, true);
        Logger.d("getAttrInteger:" + typedValue.string);
        Logger.d("getAttrInteger:" + typedValue.data);
        Logger.d("getAttrInteger:" + typedValue.type);
        return typedValue.data;
    }

    public static int getAttrResourceId(@NonNull Context context, int attrRes) {
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(attrRes, typedValue, true);
        Logger.d("getAttrResourceId:" + typedValue.resourceId);
        Logger.d("getAttrResourceId:" + typedValue.type);
        Logger.d("getAttrResourceId:" + typedValue.data);
        return typedValue.resourceId;
    }

    public static boolean getAttrBoolean(@NonNull Context context, int attrRes) {
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(attrRes, typedValue, true);
        Logger.d("getAttrInteger string:" + typedValue.string);
        Logger.d("getAttrInteger data:" + typedValue.data);
        Logger.d("getAttrInteger type:" + typedValue.type);
        return typedValue.data == -1;
    }


    public static float getAttrDim(@NonNull Context context, int attrRes) {
        TypedValue typedValue = new TypedValue();
        // 第三个参数true，实际上我看不太懂是什么作用。
        // 猜测：传入的id可能是一个引用，是否要继续解析该引用。
        // 文档中这么描述：
           /*
           If true, resource references will be walked; if
                             false, <var>outValue</var> may be a
                             TYPE_REFERENCE.  In either case, it will never
                             be a TYPE_ATTRIBUTE.
           */
        context.getTheme().resolveAttribute(attrRes, typedValue, true);
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return typedValue.getDimension(metrics);
    }

    /**
     * dp转px
     *
     * @param dpValue
     * @return
     */
    public static int dip2px(float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率 px(像素) 转 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取屏幕分辨
     *
     * @param context
     * @return
     */
    public static int[] getScreenSize(Context context) {
        DisplayMetrics metrics = getDisplayMetrics(context);
        return new int[]{metrics.widthPixels, metrics.heightPixels};
    }

    /**
     * 返回原尺寸的DisplayMetrics android 4.0默认会减掉通知栏部分
     *
     * @param context Context
     * @return DisplayMetrics
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metric);
        return metric;
    }

    public static boolean isNetworkAvailable() {
        if (App.getInstance().getApplication() == null) {
            return false;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) App.getInstance().getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            Network[] networks = connectivityManager.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                if (NetworkInfo.State.CONNECTED.equals(networkInfo.getState()))
                    return true;
            }
        }
        return false;
    }

    public static boolean dbCopy(Context context, String assetsPath, String destName) {
        try {
            // 打开 文件
            InputStream myInput = context.getAssets().open(assetsPath);
            // 获取目标文件
            File file = context.getDatabasePath(destName);
            //获取目标文件的文件夹
            File parentFile = file.getParentFile();
            // 创建文件夹
            if (!parentFile.exists()) {
                boolean mkdirs = parentFile.mkdirs();
                if (!mkdirs) {
                    return false;
                }
            }

            if (file.exists()) {
                boolean delete = file.delete();
                if (!delete) {
                    return false;
                }
            }

            if (!file.exists()) {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    return false;
                }
            }

            OutputStream myOutput = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
            return true;
        } catch (Throwable e) {
            Logger.error(e);
        }
        return false;
    }

    public static String getStringFromAssets(String fileName) {
        try {
            InputStream inputStream = App.getInstance().getApplication().getResources().getAssets().open(fileName);
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            StringBuilder Result = new StringBuilder();
            while ((line = bufReader.readLine()) != null) {
                Result.append(line);
                Result.append("\n");
            }
            inputReader.close();
            inputStream.close();
            return Result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static float getFontHeight(@NonNull Paint paint){
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }

    public static float getFontWidth(@NonNull Paint paint,String text){
        return paint.measureText(text);
    }
}
